<template autoRoute="true" funcCode="sdm.project" name="项目">
  <div class="wbs-container">
    <div style="display: flex; flex-direction: column">
      <div style="height: 45px">
        <CToolbar
          ref="ctoolbar"
          :fields="fields"
          :visibleButtons="toolbarOptions"
          :lineHeight="currentLineHeight"
          :search-fields="['name']"
          :cache-key="'project_page'"
          @updateFieldVisibility="updateFieldVisibility"
          @updateField="updateField"
          @fieldReordered="(fields: any[]) => handleFieldReordered(fields)"
          @lineHeightChanged="
            (lineHeight: any) => handleLineHeightChanged(lineHeight)
          "
          @search="handleSearch"
          @filter="handleFilter"
          @sort="
            (condition: any | null, direction: 'asc' | 'desc') =>
              handleSort(condition || {}, direction)
          "
          @openAddRecordDialog="handleAddRecordDialog"
          @save-cache-data="(cacheData: CacheData) => savePageState(cacheData)"
        >
          <!-- 示例：添加自定义按钮 -->
          <template autoRoute="true" #toolbar-right-after>
            <el-button
              style="
                margin-left: 10px;
                margin-right: 0;
                width: 100px;
                height: 32px;
              "
              type="primary"
              @click="handleCreateProject"
              ><el-icon><plus /></el-icon>
              <span style="padding-left: 3px">新建项目</span>
            </el-button>
            <ViewToggle
              style="margin-left: 10px"
              v-model="viewMode"
              @change="handleViewModeChange"
            />
          </template>
        </CToolbar>
      </div>
      <div
        style="padding: 0 20px; height: auto"
        v-if="pages.filterConditions.length > 0"
      >
        <el-tag
          v-for="tag in pages.filterConditions"
          :key="tag.field"
          closable
          type="success"
          color="#f6f7fa"
          @close="handleTagClose(tag)"
          style="margin-right: 5px; color: #86909c"
          >{{ getTagContent(tag) }}
        </el-tag>
        <el-button
          text
          type="primary"
          @click="handleTagClose(undefined)"
          style="
            height: 24px;
            padding: 5px 10px;
            font-size: 12px;
            color: #1aa1fb;
          "
          ><span>清空</span></el-button
        >
      </div>
    </div>
    <CLTabs
      v-model="activeTab"
      :items="tabItems"
      :show-add-button="showAddButton"
      @tab-added="handleTabAdded"
      @tab-removed="handleTabRemoved"
      @tab-sorted="handleTabSorted"
      @tab-activated="handleTabActivated"
    >
      <template autoRoute="true" #content="{ activeTab: tabItem }">
        <div v-if="toolbarOptions">
          <!-- 封装的Toolbar组件 -->
          <div class="wbs-tree-container" v-if="showMode === 'grid'">
            <!-- 网格视图内容 -->
            <UseSoftware
              :fields="fields"
              :software-data="tableData"
              :card-config="cardConfig"
            ></UseSoftware>
          </div>
          <!-- 任务树形结构 -->
          <div v-loading="loading" class="wbs-tree-container" v-else>
            <CLTable
              :page-query="pages"
              :fields="fields"
              :initial-data="tableData"
              :line-height="currentLineHeight"
              :router-fields="routerFields"
              :more-actions="moreActions"
              :tableConfig="tableConfig"
              :on-add-node="handleAddNode"
              :on-delete-node="handleDeleteNode"
              :on-update-node="handleUpdateNode"
              @update:initial-data="updateTableData"
              @update:saveField="updateTableData"
              @view-node-detail="handleShowRecordDetail"
              @show:records="handleShowRecords"
              @node-selected="handleNodeSelected"
              @onMoreAction="handleMoreAction"
              @pagerChange="pagerChange"
            />
          </div>
          <!-- 字段配置悬浮层 -->
          <FieldConfigPopup
            :fields="currentFields"
            :position="fieldConfigPosition"
            :visible="showFieldConfig"
            @close="showFieldConfig = false"
            @fieldsChange="
              (fields: any[], rec: any) => handleFieldsChange(fields, rec)
            "
          />
        </div>

        <!-- 新建项目弹窗 -->
        <CreateProjectTemplatesDialog
          v-model="showCreateProjectDialog"
          @create-blank="handleCreateBlankProject"
          @select-template="handleSelectTemplate"
          @manage-templates="handleManageTemplates"
        />

        <!-- 创建项目表单对话框 -->
        <CreateProjectFormDialog
          v-model="showCreateFormDialog"
          :template-id="selectedTemplateId"
          @submit="handleFormSubmit"
          @cancel="handleFormCancel"
        />
      </template>
    </CLTabs>
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, provide, reactive, ref, computed, watch } from "vue";
  import type { FormItemRule } from "element-plus";
  import { ElMessage, ElMessageBox } from "element-plus";
  import CLTabs from "@/components/CLTabs.vue";
  import CToolbar from "@/components/CToolbar.vue";
  import ViewToggle from "@/components/ViewToggle.vue";
  import CreateProjectTemplatesDialog from "@/components/CreateProjectTemplatesDialog.vue";
  import CreateProjectFormDialog from "@/components/CreateProjectFormDialog.vue";
  // import WbsTable from "./wbsTable.vue";
  import CLTable from "@/components/CLTable/index.vue";
  import FieldConfigPopup from "@/components/FieldConfigPopup.vue";
  import {
    deleteIcon,
    editIcon,
    favoriteIcon,
    settingIcon,
    visitProject,
  } from "@/utils/SvgIcons";
  import type { CacheData, FilterCondition, TabItem } from "@/data/wbsFields";
  import type { ProjectNode } from "@/data/wbsData";
  import {
    deleteProject,
    favoriteProject,
    getMyProjectTitle,
    getTableHeaderByTargetType,
    listProjectTab,
    unfavoriteProject,
  } from "@/api/project";
  import UseSoftware from "@/components/UseSoftware.vue";
  import { Plus } from "@element-plus/icons-vue";
  import { PATHTYPE, type QueryCondition } from "@/interface/project";
  import { getProjectConfig, saveProjectConfig } from "../design/api";
  import { useRouter } from "vue-router";
  import { typexToType } from "@/utils/common.ts";

  // 重新定义本地的DynamicField类型，确保类型兼容性
  interface DynamicField {
    id: number;
    name: string;
    field: string;
    type: string;
    invisible: boolean;
    options?: Array<{ value: string; label: string; tag?: string }>;
    rules?: FormItemRule[];
    typex?: string;
  }

  const pages = reactive<CacheData>({
    pageNo: 1,
    pageSize: 20,
    total: 10,
    filterConditions: [],
    sortCondition: {
      condition: null,
      direction: "asc",
    },
    lineHeight: "medium",
  });

  // 标签页数据
  const activeTab = ref<number>(1);
  const tabItems = ref<TabItem[]>([
    {
      id: 1,
      title: "全部项目",
      closable: false,
      type: "ALL",
    },
    {
      id: 2,
      title: "我管理的",
      closable: false,
      type: "CURATED",
    },
    {
      id: 3,
      title: "我参与的",
      closable: false,
      type: "PARTICIPATED",
    },
    {
      id: 4,
      title: "我收藏的",
      closable: false,
      type: "FAVORITE",
    },
  ]);
  const showAddButton = ref(false);
  // 初始化字段数据并转换为本地的DynamicField类型
  const fields = ref<DynamicField[]>([]);
  const routerFields = ref(["name"]);
  // const routerFields = ref([]);
  const moreActions: any[] = [
    { key: "visit", label: "访问项目", icon: visitProject },
    {
      key: "favorite",
      label: ["收藏项目", "取消收藏"],
      icon: favoriteIcon,
      color: ["", "#ff6b6b"],
      switchField: { field: "favorite", value: "YES" },
      invisible: ["children"],
    },
    { key: "edit", label: "编辑", icon: editIcon },
    { key: "setting", label: "项目设置", icon: settingIcon },
    { key: "recycle", label: "回收站", icon: deleteIcon, color: "#D54941" },
  ];

  const router = useRouter();

  const tableConfig = ref({
    editable: false, // 表格是否可编辑
    borderMode: "none",
    defaultRowHeight: 56,
    tableH: computed(() => dynamicTableHeight.value),
    page: {
      enable: true,
      pageSizes: [5, 10, 20, 50, 100],
      pageSize: pages.pageSize,
      total: pages.total,
      // layout: "total, sizes, prev, pager, next, jumper",
    },
    // typeIconShow: true,
    // showOperationsColumn: true, // 是否显示操作列
    // OperationsColumnMode: "text", // 操作列模式，text为文本模式
    // OperationsColumnWidth: 350, //自定义操作列宽度
    frozenColCount: 3, // 冻结前面列数
    rightFrozenColCount: 1, // 冻结后面列数
    tree: {
      enabled: false, // 开启树形结构
      column: 2, // 开启的树形结构的列索引
    },
    rowSeriesNumber: {},
    tableType: "project",
    // borderMode: "none", // 表格边框模式，none为无边框
  });
  const cardConfig = ref({
    needFields: ["id", "name", "projectManager", "startDate"],
    moreActions: [
      { key: "visit", label: "访问项目" },
      { key: "favorite", label: "收藏项目" },
      { key: "edit", label: "编辑项目" },
      { key: "setting", label: "项目设置" },
      { key: "recycle", label: "回收站" },
    ],
  });
  // 工具栏选项
  const toolbarOptions = ref({
    fieldConfig: false,
    filter: true,
    sort: true,
    lineHeight: true,
    search: {
      name: "请输入项目名称搜索",
      enable: true,
    },
    // help: true,
    // log: true,
    // export: true,
  });

  const showRecordDetailDialog = ref(false);
  // 字段配置弹窗相关状态
  const showFieldConfig = ref(false);
  const fieldConfigPosition = ref({ left: 0, top: 0 });
  const currentFields = ref<DynamicField[]>([]);

  // 初始化表格数据，将从父组件传递给wbsTable
  const tableData = ref<ProjectNode[]>([]);
  // 当前行高设置
  const currentLineHeight = ref<"low" | "medium" | "high">("medium");

  // Loading状态管理
  const loading = ref(true);

  // 动态计算表格高度
  const dynamicTableHeight = computed(() => {
    // 基础高度计算
    let baseHeight = 153;
    if (pages.filterConditions.length > 0) {
      baseHeight += 24;
    }
    return `calc(100vh - ${baseHeight}px)`;
  });

  // 视图模式
  const viewMode = ref<"list" | "grid">("list");

  // 新建项目弹窗相关
  const showCreateProjectDialog = ref(false);
  const showCreateFormDialog = ref(false);
  const selectedTemplateId = ref<string>();
  const currentTab = ref<PATHTYPE>(PATHTYPE.All);

  // 从后端获取字段数据（带 sessionStorage 缓存）
  const fetchFields = async () => {
    // TODO: 这里还没有完善
    // let res = await getProjectConfig("PROJECT");
    // let result = [];
    // result = res.pageValue ? JSON.parse(res.pageValue) : [];
    const response = await getTableHeaderByTargetType("PROJECT_BASE_FIELD");
    let result = JSON.parse(response?.config || []);
    if (!result.length) {
      // 调用真实的API获取表头配置
      // targetType 可以根据实际业务需求传入，例如 'project'
      const response = await getTableHeaderByTargetType("PROJECT_BASE_FIELD");
      result = JSON.parse(response?.config || []);
    }
    fields.value = result?.map((config: Record<string, any>) => {
      const options = [];
      if (config.lifeCycleStatus) {
        const ops = tableData.value.find((i: any) => i.transferEdge);
        if (ops && Array.isArray(ops)) {
          options.push(...ops);
        }
      }
      const uiType = config?.uiType?.toLowerCase();
      const opts = options.length
        ? options
        : Array.isArray(config.option)
          ? config.option
          : JSON.parse(config.option || "[]");

      let checkedText = "";
      let uncheckedText = "";
      let checked = false;
      switch (uiType) {
        case "switch":
          checkedText = opts["checkedText"];
          uncheckedText = opts["uncheckedText"];
          checked = opts["checked"] === "YES";
          break;
        case "checkbox":
          checked = opts["checked"];

          break;
        default:
          break;
      }

      return {
        ...config,
        field:
          config?.code === "lifecycleStatusType" ? "taskStatus" : config?.code,
        name: config?.displayName,
        type: config?.uiType?.toLowerCase(),
        invisible: !!config?.invisible,
        disable: true,
        checkedText,
        uncheckedText,
        checked,
        options: opts,
      };
    });
    console.log(fields.value, "fields");
  };

  const pagerChange = (params: { currentPage: number; pageSize: number }) => {
    pages.pageNo = params.currentPage;
    pages.pageSize = params.pageSize;
    fetchTableData(currentTab.value);
    // 保存状态
    savePageState();
  };
  // 驼峰转下划线函数
  const camelToSnake = (str: string): string => {
    return str.replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`);
  };
  // 从后端获取表格数据
  const fetchTableData = async (path: PATHTYPE) => {
    loading.value = true;
    let params: any = {
      pageNo: pages.pageNo,
      pageSize: pages.pageSize,
      conditions: pages.filterConditions,
      // logic: "AND",
    };
    if (pages.sortCondition.condition?.field) {
      params.sortParams = [
        {
          asc: pages.sortCondition.direction === "asc",
          field: camelToSnake(pages.sortCondition.condition.field),
        },
      ];
    }
    // const a = params.conditions.filter(
    //   (i: any) => i.field === "relatedMe" || i.field === "archivedStatue",
    // );
    // params.conditions = params.conditions.filter(
    //   (i: any) => !(i.field === "relatedMe" || i.field === "archivedStatue"),
    // );
    let type = [];
    // type = a.reduce((acc: any[], i: any) => {
    //   if (Array.isArray(i.value)) {
    //     acc.push(...i.value);
    //   } else {
    //     acc.push(i.value);
    //   }
    //   return acc;
    // }, []);
    if (path) type.push(path);
    console.log("请求参数:", params);
    try {
      const res: any = await listProjectTab(params, type);
      // 兼容不同返回结构：优先使用 res.list，否则使用 res.data/list/records 等常见字段
      res?.result?.forEach((i: any) => {
        if (i.name && typeof i.name === "object" && i.name["zh_CN"]) {
          i.name = i.name["zh_CN"];
        }

        i.creatorObject = i.creatorObject["name"];
      });
      tableData.value = Array.isArray(res.result) ? res.result : [];
      console.log("表格数据:", tableData.value);
      pages.total = res.total;
      // 刷新统计数据
      if (path === PATHTYPE.All) fetchProjectStats(path);
    } catch (error) {
      console.error("获取项目数据失败:", error);
    } finally {
      loading.value = false;
    }
  };

  // 获取项目统计数据
  const fetchProjectStats = async (path: PATHTYPE) => {
    try {
      const params = {
        pageNo: pages.pageNo,
        pageSize: pages.pageSize,
        conditions: pages.filterConditions,
        logic: "AND",
      };
      // const a = params.conditions.filter(
      //   (i: any) => i.field === "relatedMe" || i.field === "archivedStatue",
      // );
      // params.conditions = params.conditions.filter(
      //   (i: any) => !(i.field === "relatedMe" || i.field === "archivedStatue"),
      // );
      let type = [];
      // type = a.reduce((acc: any[], i: any) => {
      //   if (Array.isArray(i.value)) {
      //     acc.push(...i.value);
      //   } else {
      //     acc.push(i.value);
      //   }
      //   return acc;
      // }, []);
      if (path) type.push(path);
      const stats = await getMyProjectTitle(params, type);
      tabItems.value.forEach((i: any) => {
        let type = i.type.toLowerCase();
        if (type === "all") type = "all1";
        // 过滤掉括号以及括号内的内容
        i.title = i.title.replace(/\([^)]*\)/g, "");
        i.title = `${i.title}(${stats[type as keyof typeof stats] || 0})`;
      });
      console.log("项目统计数据:", stats);
    } catch (error) {
      console.error("获取项目统计数据失败:", error);
    }
  };

  // 添加节点的钩子函数
  const handleAddNode = (parentNode: ProjectNode, newNode: ProjectNode) => {
    console.log("添加节点:", parentNode, newNode);

    // 实际项目中，这里应该调用API保存数据
    // 例如: await axios.post('/api/wbs/add', { parentId: parentNode.id, node: newNode });

    // 这里仅作前端演示，实际添加逻辑由wbsTable组件内部处理
    // 如果需要在父组件中处理添加逻辑，可以在这里实现
  };

  // 处理删除项目的钩子函数
  const handleDeleteNode = async (node: ProjectNode) => {
    console.log("删除项目:", node);

    try {
      await deleteProject(node.id);
      ElMessage.success("项目删除成功");
      // 删除成功后刷新项目列表
      fetchTableData();
    } catch (error) {
      console.error("删除项目失败:", error);
      ElMessage.error("删除项目失败");
    }
  };

  // 处理收藏项目的钩子函数
  const handleFavoriteProject = async (node: ProjectNode) => {
    console.log("收藏项目:", node);
    loading.value = true;
    try {
      await favoriteProject(node.id);

      pages.pageNo = 1;
      fetchTableData(currentTab.value);
      ElMessage.success("收藏成功");
    } catch (error) {
      console.error("收藏项目失败:", error);
      ElMessage.error("收藏操作失败");
    } finally {
      loading.value = false;
    }
  };

  // 处理取消收藏项目的钩子函数
  const handleUnfavoriteProject = async (node: ProjectNode) => {
    console.log("取消收藏项目:", node);
    loading.value = true;
    try {
      await unfavoriteProject(node.id);
      pages.pageNo = 1;
      fetchTableData(currentTab.value);
    } catch (error) {
      console.error("取消收藏项目失败:", error);
      ElMessage.error("取消收藏操作失败");
    } finally {
      loading.value = false;
    }
  };

  // 更新节点的钩子函数
  const handleUpdateNode = (node: ProjectNode, field: string, value: any) => {
    console.log("更新节点:", node, field, value);

    // 实际项目中，这里应该调用API更新数据
    // 例如: await axios.put('/api/wbs/update', { id: node.id, field, value });

    // 这里仅作前端演示，实际更新逻辑由wbsTable组件内部处理
    // 如果需要在父组件中处理更新逻辑，可以在这里实现
  };

  // 更新表格数据的函数
  const updateTableData = (data: ProjectNode[]) => {
    console.log("表格数据更新:", data);
    // tableData.value = data;

    // 实际项目中，这里可以选择是否保存更新后的数据到后端
    // 例如: await axios.post('/api/wbs/save-all', data);
  };

  // 更新字段可见性状态
  const updateFieldVisibility = (fieldId: string, invisible: boolean) => {
    console.log("更新字段可见性:", fields, invisible);
    const field = fields.value.find((f) => f.field === fieldId);
    if (field) {
      field.invisible = invisible;
    }
  };
  // 保存页面状态到缓存
  const savePageState = (cache?: CacheData) => {
    try {
      const state = {
        filterConditions: pages.filterConditions,
        sortCondition: cache?.sortCondition || pages.sortCondition,
        pageNo: pages.pageNo,
        pageSize: pages.pageSize,
        activeTab: activeTab.value,
        viewMode: viewMode.value,
        lineHeight: cache?.lineHeight || currentLineHeight.value,
      };
      if (!state.sortCondition.condition) state.sortCondition = null;
      console.log("保存页面状态:", state);
      sessionStorage.setItem(
        "toolbar_cache_project_page",
        JSON.stringify(state),
      );
    } catch (e) {
      console.error("保存页面状态失败:", e);
    }
  };
  // 从缓存恢复页面状态
  const restorePageState = () => {
    try {
      const cachedState = sessionStorage.getItem("toolbar_cache_project_page");
      console.log("缓存状态:", cachedState);
      if (cachedState) {
        const state = JSON.parse(cachedState);
        if (state.filterConditions)
          pages.filterConditions = state.filterConditions;
        if (state.sortParams) pages.sortCondition = state.sortParams;
        if (state.pageNo) pages.pageNo = state.pageNo;
        if (state.pageSize) pages.pageSize = state.pageSize;
        if (state.activeTab) activeTab.value = state.activeTab;
        if (state.viewMode) viewMode.value = state.viewMode;
        if (state.lineHeight) currentLineHeight.value = state.lineHeight;
        console.log("恢复页面状态:", pages);
      }
      console.log("页面状态:", pages);
    } catch (e) {
      console.error("恢复页面状态失败:", e);
    }
  };
  // 辅助函数：添加或更新条件
  const addOrUpdateCondition = (
    fieldName: string,
    operator: string,
    value: any,
  ) => {
    // 先清除该字段的现有条件
    clearConditionByField(fieldName);
    // 添加新条件
    pages.filterConditions.push({
      field: fieldName,
      operator: operator,
      value: value,
    });
  };

  // 辅助函数：清除指定字段的条件
  const clearConditionByField = (fieldName: string) => {
    pages.filterConditions = pages.filterConditions.filter(
      (condition) => condition.field !== fieldName,
    );
  };
  // 处理搜索事件
  const handleSearch = (keyword: string, searchFields?: string[]) => {
    console.log("搜索关键词:", keyword);
    console.log("搜索字段:", searchFields);
    // 实际项目中，这里可以调用API搜索数据
    // 例如: await axios.get('/api/wbs/search', { params: { keyword, searchFields } });

    // 前端搜索实现 - 过滤表格数据
    // 如果有搜索关键词，添加搜索条件
    if (keyword && keyword.trim()) {
      addOrUpdateCondition(
        searchFields ? searchFields[0] : "name",
        "like",
        keyword.trim(),
      );
    } else {
      // 如果搜索关键词为空，清除搜索条件
      clearConditionByField(searchFields ? searchFields[0] : "name");
    }
    // 重置到第一页
    pages.pageNo = 1;
    console.log("关键词为空，恢复原始数据");
    // 如果关键词为空，恢复原始数据
    fetchTableData(currentTab.value);
    // 保存状态
    savePageState();
  };

  // 处理排序事件
  // 用于存储用户选择的节点
  const selectedNodes = ref<ProjectNode[]>([]);

  // 处理节点选择事件
  const handleNodeSelected = (nodes: ProjectNode[]) => {
    selectedNodes.value = nodes;
  };

  // 处理更多操作
  const handleMoreAction = async (action: string, node: ProjectNode) => {
    console.log(action, "-----");

    try {
      switch (action) {
        case "recycle":
          // 确认删除
          await ElMessageBox.confirm(
            `确定要删除项目"${node.name}"到回收站吗？`,
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
            },
          );
          await handleDeleteNode(node);
          break;

        case "view":
          handleShowRecordDetail(node);
          break;

        case "favorite":
          console.log(node, "---");
          if (node?.favorite === "YES") {
            await handleUnfavoriteProject(node);
          } else {
            await handleFavoriteProject(node);
          }
          break;

        case "visit":
          // 访问项目逻辑
          console.log("访问项目:", node);
          if (node && node.id) {
            await router.push({
              path: "/wbs",
              query: {
                projectId: node.id,
                tab: 1,
              },
            });
          }
          break;

        case "edit":
          // 编辑项目逻辑
          console.log("编辑项目:", node);
          if (node && node.id) {
            router.push({
              path: "/pm/setting/baseInfo",
              query: { projectId: node.id },
            });
          }
          break;

        case "setting":
          // 项目设置逻辑
          console.log("项目设置:", node);
          ElMessage.info("项目设置功能待实现");
          break;

        // case "recycle":
        //   // 回收站逻辑
        //   console.log("移入回收站:", node);
        //   ElMessage.info("回收站功能待实现");
        //   break;

        case "name":
          console.log("跳转到任务wbs表格：", node);
          await router.push({
            path: "/wbs",
            query: {
              projectId: node.id,
              tab: 1,
            },
          });
          break;

        default:
          console.warn("未知操作:", action);
      }
    } catch (error) {
      if (error !== "cancel") {
        console.error("操作失败:", error);
        ElMessage.error("操作失败，请重试");
      }
    }
  };

  // 批量操作相关状态
  const selectedRecords = ref<ProjectNode[]>([]);
  const showCLBatchOpToolbar = ref(false);
  const showCLBatchOpToolbarGantt = ref(false);

  const handleShowRecords = (records: ProjectNode[]) => {
    console.log("handleShowRecords", records);
    selectedRecords.value = records;
    showCLBatchOpToolbar.value = records.length > 0;
    showCLBatchOpToolbarGantt.value = records.length > 0;
  };

  // 处理批量删除操作
  const handleBatchDelete = () => {
    if (selectedRecords.value.length === 0) return;

    // 调用删除节点的函数处理批量删除
    selectedRecords.value.forEach((record) => {
      handleDeleteNode(record);
    });

    // 删除完成后清空选中状态
    selectedRecords.value = [];
    showCLBatchOpToolbar.value = false;
    showCLBatchOpToolbarGantt.value = false;
  };

  const handleSort = (
    condition: DynamicField | null,
    direction: "asc" | "desc",
  ) => {
    console.log("排序条件:", condition, "排序方向:", direction);
    if (condition) {
      pages.sortCondition = {
        direction: direction,
        condition: condition,
      };
    } else {
      // 清除排序参数
      pages.sortCondition = {};
    }
    fetchTableData(currentTab.value);
    // 保存状态
    savePageState();
  };

  // 处理筛选事件
  const handleFilter = (conditions: any[]) => {
    // 合并搜索条件和筛选条件
    pages.filterConditions = (conditions || []).map((condition) => ({
      field: condition.field,
      operator: condition.operator || "=",
      value: condition.value, // 转换为project模块的value结构
    }));
    console.log("合并后的筛选条件:", conditions, pages.filterConditions);
    // 重置到第一页
    pages.pageNo = 1;
    fetchTableData(currentTab.value);
    // 保存状态
    savePageState();
  };

  // 更新字段数据
  const updateField = (
    fieldId: number,
    updatedData: DynamicField & { options?: any[] },
  ) => {
    console.log("更新字段:", fieldId, updatedData);
    const field = fields.value.find((f) => f.id === fieldId);
    if (field) {
      Object.assign(field, updatedData);

      if (
        updatedData.options &&
        (field.typex === "radio" || field.typex === "multiple")
      ) {
        console.log(`更新字段"${field.name}"的选项，刷新表格数据`);
        // 创建一个新的数组引用
        tableData.value = [...tableData.value];
      }
    }
  };

  // 处理字段重排序事件
  const handleFieldReordered = (reorderedFields: DynamicField[]) => {
    console.log(
      "处理字段重排序:",
      reorderedFields.map((f) => f.name),
    );
    fields.value = [...reorderedFields];
    // 同步到缓存
    try {
      sessionStorage.setItem(
        "FIELDS_CACHE_PROJECT",
        JSON.stringify(fields.value || []),
      );
    } catch (e) {}
  };

  // 标签页相关处理函数
  const handleTabAdded = (tab: TabItem) => {
    console.log("标签页添加:", tab);
  };

  const handleTabRemoved = (tab: TabItem) => {
    console.log("标签页移除:", tab);
  };

  const handleTabSorted = (tabs: TabItem[]) => {
    console.log("标签页排序:", tabs);
    tabItems.value = tabs;
  };

  const handleTabActivated = (tabId: number) => {
    console.log("标签页激活:", tabId);
    const curItem = tabItems.value.find((item) => item.id === tabId);
    activeTab.value = tabId;
    fetchTableData(curItem?.type as PATHTYPE);
    currentTab.value = curItem?.type as PATHTYPE;
    // 保存状态
    savePageState();
  };
  const showMode = ref<string>("list");
  // 处理视图模式变化
  const handleViewModeChange = (mode: "list" | "grid") => {
    console.log("视图模式切换:", mode);
    // 这里可以根据视图模式调整表格显示方式
    // 例如：切换到网格视图时显示卡片布局
    showMode.value = mode;
    // 保存状态
    savePageState();
  };

  // 处理新建项目
  const handleCreateProject = () => {
    showCreateProjectDialog.value = true;
  };

  // 处理创建空白项目
  const handleCreateBlankProject = () => {
    console.log("点击创建空白项目");
    selectedTemplateId.value = undefined;
    showCreateProjectDialog.value = false; // 关闭模板选择对话框
    showCreateFormDialog.value = true; // 打开表单对话框
    console.log("showCreateFormDialog.value:", showCreateFormDialog.value);
  };

  // 处理选择模板
  const handleSelectTemplate = (template: any) => {
    selectedTemplateId.value = template.id;
    showCreateProjectDialog.value = false; // 关闭模板选择对话框
    showCreateFormDialog.value = true; // 打开表单对话框
  };

  // 处理表单提交
  const handleFormSubmit = (formData: any) => {
    console.log("项目创建成功:", formData);
    console.log("模板ID:", selectedTemplateId.value);

    // 项目创建成功后，刷新表格数据
    fetchTableData(currentTab.value);

    // 重置状态
    showCreateFormDialog.value = false;
    selectedTemplateId.value = undefined;
  };

  // 处理表单取消
  const handleFormCancel = () => {
    showCreateProjectDialog.value = true; // 返回模板选择对话框
    showCreateFormDialog.value = false;
  };

  // 处理模板管理
  const handleManageTemplates = () => {
    console.log("管理模板");
    // 这里可以跳转到模板管理页面
    // router.push('/template-management');
  };

  // 处理行高变化事件
  const handleLineHeightChanged = (lineHeight: "low" | "medium" | "high") => {
    console.log("行高已变更为:", lineHeight);
    currentLineHeight.value = lineHeight;
    // 保存状态
    savePageState();
  };

  // 处理字段配置变化
  const handleFieldsChange = async (
    updatedFields: DynamicField[],
    args: { field: string; invisible: boolean },
  ) => {
    // 更新本地字段配置，确保拖拽后能同步显示
    currentFields.value = JSON.parse(JSON.stringify(updatedFields));
    console.log("字段配置已更新:", updatedFields);
    fields.value = [...updatedFields];
    const params = {
      pageKey: "PROJECT", // args.field,
      pageValue: JSON.stringify(fields.value),
    };
    await saveProjectConfig(params);
    // 同步到缓存
    try {
      sessionStorage.setItem(
        "FIELDS_CACHE_PROJECT",
        JSON.stringify(fields.value || []),
      );
    } catch (e) {}
  };

  // 显示字段配置弹窗
  const showFieldConfigPopup = (position: { left: number; top: number }) => {
    fieldConfigPosition.value = position;
    currentFields.value = JSON.parse(JSON.stringify(fields.value || []));
    setTimeout(() => {
      showFieldConfig.value = !showFieldConfig.value;
    }, 100);
  };
  const addRecord = (newRecords: ProjectNode[]) => {
    tableData.value = [...newRecords];
  };
  const showAddRecordDialog = ref("0%");
  const handleAddRecordDialog = () => {
    showAddRecordDialog.value = "55%";
  };
  const selectedRecord = ref<ProjectNode>();
  const handleShowRecordDetail = (record: ProjectNode) => {
    selectedRecord.value = record;
    showRecordDetailDialog.value = true;
  };
  const closeRecordDialog = () => {
    showAddRecordDialog.value = "0%";
  };
  const ctoolbar = ref();
  const labels: Record<string, string> = {
    "=": "等于",
    "!=": "不等于",
    like: "包含",
    not_contains: "不包含",
    ">": "大于",
    "<": "小于",
  };
  const handleTagClose = (tag: FilterCondition | undefined) => {
    console.log("关闭标签:", tag);
    if (tag) {
      pages.filterConditions = pages.filterConditions.filter(
        (item) => item.field !== tag.field,
      );
    } else {
      pages.filterConditions = [];
    }
    ctoolbar.value.filterConditions = pages.filterConditions;
    ctoolbar.value.applyFilter();
  };
  const getTagContent = (tag: FilterCondition) => {
    const file = fields.value.find((f) => f.field === tag.field);
    const fieldName = file?.name;
    const operator = labels[tag.operator];
    return `${fieldName}  ${operator} "${tag.value}"`;
  };
  // 提供给所有子孙组件使用
  provide("addRecord", addRecord);
  provide("showFieldConfigPopup", showFieldConfigPopup);

  // 组件挂载时获取字段数据和表格数据
  onMounted(async () => {
    restorePageState();
    await fetchFields();
    // 恢复页面状态
    // 根据恢复的状态获取表格数据
    const curItem = tabItems.value.find((item) => item.id === activeTab.value);
    await fetchTableData(curItem?.type as PATHTYPE);
  });
</script>

<style scoped>
  .wbs-container {
    background-color: #ffffff;
    position: relative;
  }

  .wbs-tree-container {
    background-color: #fff;
    padding: 0 20px;
    position: relative;
  }

  .loading-container {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 400px;
    background-color: #fff;
  }

  .batch-btn {
    padding: 4px 12px;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 12px;
    color: #42464e;
  }

  .batch-btn:hover {
    color: #42464e;
    background-color: rgba(31, 35, 41, 0.1);
  }

  /* 滚动条样式 */
  .wbs-tree-container::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  .wbs-tree-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  .wbs-tree-container::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
  }

  .wbs-tree-container::-webkit-scrollbar-thumb:hover {
    background: #555;
  }

  .activity-section {
    margin-top: 16px;
    height: 400px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }
  /*因为project顶部与标签页切换要有一定距离，所以这样设置*/
  :deep(.batch-operations-layer) {
    top: 16px;
  }
</style>
<style lang="scss">
  .table-container {
    .el-select__wrapper {
      box-shadow: none !important;
      font-size: 12px;
    }
    .el-select-dropdown__item {
      font-size: 12px;
    }
  }
  .el-tag .el-tag__close {
    color: #86909c;
  }
  .el-tag .el-tag__close:hover {
    background-color: #42464e;
  }
</style>
